package com.little.g.springcloud.mall.web.controller;

import com.little.g.springcloud.common.utils.CharUtil;
import com.little.g.springcloud.common.utils.ResponseUtil;
import com.little.g.springcloud.mall.api.LitemallStorageService;
import com.little.g.springcloud.mall.api.StorageService;
import com.little.g.springcloud.mall.dto.LitemallStorageDTO;
import com.little.g.springcloud.mall.util.MyByteArrayInputStream;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 对象存储服务
 */
@Api("对象存储服务")
@RestController
@RequestMapping("/storage")
@Validated
@Slf4j
public class StorageColntroller {

	@Reference
	private StorageService storageService;

	@Reference
	private LitemallStorageService litemallStorageService;

	private String generateKey(String originalFilename) {
		int index = originalFilename.lastIndexOf('.');
		String suffix = originalFilename.substring(index);

		String key = null;
		LitemallStorageDTO storageInfo = null;

		do {
			key = CharUtil.getRandomString(20) + suffix;
			storageInfo = litemallStorageService.findByKey(key);
		}
		while (storageInfo != null);

		return key;
	}

	@ApiOperation("上传")
	@PostMapping("/upload")
	public Object upload(@RequestParam("file") MultipartFile file) throws IOException {
		String originalFilename = file.getOriginalFilename();

		LitemallStorageDTO litemallStorage = storageService.store(
				new MyByteArrayInputStream(file.getBytes()), file.getSize(),
				file.getContentType(), originalFilename);
		return ResponseUtil.ok(litemallStorage);
	}

	/**
	 * 访问存储对象
	 * @param key 存储对象key
	 * @return
	 */
	@ApiOperation("访问存储对象")
	@GetMapping("/fetch/{key:.+}")
	public ResponseEntity<Resource> fetch(@PathVariable String key) {
		LitemallStorageDTO litemallStorage = litemallStorageService.findByKey(key);
		if (key == null) {
			return ResponseEntity.notFound().build();
		}
		if (key.contains("../")) {
			return ResponseEntity.badRequest().build();
		}
		String type = litemallStorage.getType();
		MediaType mediaType = MediaType.parseMediaType(type);

		Resource file = storageService.loadAsResource(key);
		if (file == null) {
			return ResponseEntity.notFound().build();
		}
		return ResponseEntity.ok().contentType(mediaType).body(file);
	}

	/**
	 * 访问存储对象
	 * @param key 存储对象key
	 * @return
	 */
	@ApiOperation("下载存储对象")
	@GetMapping("/download/{key:.+}")
	public ResponseEntity<Resource> download(@PathVariable String key) {
		LitemallStorageDTO litemallStorage = litemallStorageService.findByKey(key);
		if (key == null) {
			return ResponseEntity.notFound().build();
		}
		if (key.contains("../")) {
			return ResponseEntity.badRequest().build();
		}

		String type = litemallStorage.getType();
		MediaType mediaType = MediaType.parseMediaType(type);

		Resource file = storageService.loadAsResource(key);
		if (file == null) {
			return ResponseEntity.notFound().build();
		}
		return ResponseEntity.ok().contentType(mediaType)
				.header(HttpHeaders.CONTENT_DISPOSITION,
						"attachment; filename=\"" + file.getFilename() + "\"")
				.body(file);
	}

}
